import { ProTable, type ProColumns } from '@ant-design/pro-components';
import {
    Button,
    Card,
    Col, Collapse,
    Drawer,
    Flex,
    Form,
    Input,
    notification,
    Radio,
    Row,
    Select,
    Upload,
    UploadProps,
} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {getAllCategoryListUsingGet} from "@/services/openAPI-backend/categoryController";
import {PlusOutlined} from "@ant-design/icons";
import {uploadUsingPost} from "@/services/openAPI-backend/upLoadController";
import MDEditor from '@uiw/react-md-editor';
import {updateArticleUsingPost} from "@/services/openAPI-backend/articleController";
export type Props = {
    data:  Record<string, any>[];
    onCancel: () => void;
    onSubmit: (values: API.InterfaceInfo) => Promise<void>;
    isOpen: boolean;
};

const EditModal: React.FC<Props> = (props) => {
    const { isOpen, data, onCancel, onSubmit } = props;
    const [categoryList, setCategoryList] = useState<API.CategoryVo[]>([]);
    const [value, setValue] = useState(data?.content);
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>(data?.thumbnail);
    const [articleContent, setArticleContent] = React.useState('');
    const formRef = useRef(null);
    const customRequest = async (image) => {
        console.log("这是断点");
        const form = new FormData();
        form.append('image', image.file);

        // form 对象 就是我们上传接口需要的参数
        // 调用api接口进行请求 , uploadFile 是走我们封装的 请求的 , 请求头 token 都包含
        try {
            const res = await uploadUsingPost(form);
            setImageUrl(res.data);
            notification.info({
                message: '系统提示',
                description: '图片上传成功',
                placement: 'topRight',
                duration: 2,
            });
        } catch (e) {
            notification.info({
                message: '系统提示',
                description: '图片上传失败',
                placement: 'topRight',
                duration: 2,
            });
        }
        // 拿到调取接口返回的数据
    };
    const handleChange: UploadProps['onChange'] = (info) => {
        console.log("断点")
        if (info?.file?.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info?.file?.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj as FileType, (url) => {
                setLoading(false);
                setImageUrl(url);
            });
        }
    };
    const uploadProps = {
        name: 'image', //取值必须和接口参数中的文件参数名相同： MultipartFile file
        multiple: true,
        showUploadList: false,
        customRequest: customRequest,
    };
    const uploadButton = (
        <button style={{ border:0, background: 'none', marginTop: 0,width: 150,height: 150 }} size={'large'} type="button">
            <PlusOutlined/>
            <div style={{ marginTop: 0 }}>Upload</div>
        </button>
    );


// 定义handleContentChange函数
    const handleContentChange = (value: string, recordId: number | string) => {
        // 更新文章内容状态
        setArticleContent(value);

    };
    const onCollpseChange = (key: string | string[]) => {
        console.log(key);
    };
    const onFinish = async (values: any) => {
        const res = await updateArticleUsingPost({
            ...values,
            id: data?.id,
            status: data?.status,
            thumbnail: imageUrl,
        })
        if (res?.data) {

            notification.success({
                message: '系统提示',
                description: '修改成功',
                placement: 'topRight',
                duration: 2,
            });
            onCancel();
        }else {
            notification.error({
                message: '系统提示',
                description: '修改失败',
                placement: 'topRight',
                duration: 2,
            });
        }
    };
    const loadCategoryList = async () => {
        const res = await getAllCategoryListUsingGet();
        if (res?.data) {
            setCategoryList(res?.data);
        }
    };
    const onChange = (value: number) => {
        console.log(`selected ${value}`);

    };
    const onSearch = (value: string) => {
        console.log('search:', value);
    };
    const reset = () =>{
        loadCategoryList();
        setImageUrl(data?.thumbnail)
        formRef.current?.setFieldsValue({
            title: data?.title,
            categoryId: data?.categoryId,
            content: data?.content,
            summary: data?.summary,
            isComment: data?.isComment,
        });
        setValue(data?.content);
    }
    useEffect(() => {
        reset();
        console.log(data)
    }, [data]);
    return (
        <Drawer width={"1000px"} open={isOpen}  onClose={onCancel}  footer={null}    style={{
            borderBottomLeftRadius: '10px',
            borderTopLeftRadius: '10px',
            borderWidth: '0px',
            borderTop: 0,
            borderLeft: 0,
            borderRight: 0,
            borderBottom: 0,
        }}>

          <Form ref={formRef}
                name={"basic"}
                layout="horizontal"
                onFinish={onFinish}
                style={{ maxWidth: "100%" }}>
              <Form.Item  name={"thumbnail"} label="文章封面"  valuePropName="fileList"
                         getValueFromEvent={e => {
                             if (Array.isArray(e)) {
                                 return e;
                             }
                             return e && e.fileList;
                         }}>

                  <Upload
                      {...uploadProps}
                      name="avatar"
                      listType="picture"
                      className="avatar-uploader"
                      onChange={handleChange}
                      style={{
                          marginLeft: 0,
                          width: '400px',
                          height: '400px',
                          border: 'none',
                      }}
                  >
                      {imageUrl ? (
                          <img
                              src={imageUrl}
                              alt="avatar"
                              style={{ width: 100, height: 110, marginLeft: 0 }}
                          />
                      ) : (
                          uploadButton
                      )}
                  </Upload>
              </Form.Item>
            <Row gutter={24}>
                <Col span={8}>
              <Form.Item name={"title"} label="文章标题" rules={[{ required: true, message: '请输入标题' }]}>
                  <Input />
              </Form.Item>
                </Col>
                <Col span={6}>
              <Form.Item name={"categoryId"} label="类型" rules={[{ required: true, message: '请选择相应类型' }]}>
                  <Select
                      showSearch
                      placeholder="Select a label"
                      optionFilterProp="label"
                      onChange={onChange}
                      onSearch={onSearch}
                      options={categoryList.map((item) => ({
                          label: item.name,
                          value: item.id,
                      }))}
                  />
              </Form.Item>
                </Col>
           <Col span={8}>
              <Form.Item name={"isComment"} label="是否允许评论" >
                  <Radio.Group>
                      <Radio value={1}> 允许 </Radio>
                      <Radio value={0}> 不允许 </Radio>
                  </Radio.Group>
              </Form.Item>
           </Col>
            </Row>


              <Form.Item name={"summary"} label="文章简介" rules={[{ required: true, message: '请输入简介' }]}>
                  <Input.TextArea size={"large"} />
              </Form.Item>
              <Form.Item name={"content"} label="文章内容" rules={[{ required: true, message: '文章不能为空' }]}>
                  <div className="container">
                      <MDEditor
                          value={value}
                          onChange={setValue}
                          preview={'edit'}
                          height={500}
                      />

                  </div>

              </Form.Item>
              <Form.Item>
                  <Flex justify={'right'}>
                      <Button  type="primary" htmlType="submit">
                          提交
                      </Button>
                      <Button style={{marginLeft: '10px'}} type="primary" onClick={()=>{reset()}}>
                          重置
                      </Button>
                  </Flex>
              </Form.Item>
              <Collapse ghost={true} style={{marginBottom: '20px'}} defaultActiveKey= {["1"]} items={[{key: "1" ,label:"文章效果展示",
             children: <Card>
                  <MDEditor.Markdown source={value} style={{whiteSpace: 'pre-wrap'}}/>
              </Card>}]} onChange={onCollpseChange} collapsible={"header"}>

              </Collapse>
          </Form>
        </Drawer>
    );
};

export default EditModal;
